import sys
import traceback

#observer pattern
class Observer:
    def __init__(self):
        pass
    def update(self, theChangedSubject):
        pass

class Subject:
    def __init__(self):
        self.observerList = []
    def attach(self, observer):
        self.observerList.append(observer)
    def detach(self, observer):
        try:
            self.observerList.remove(observer)
        except ValueError: #ignore if x not in list
            pass
    def notify(self, *args):
        for observer in self.observerList:
            try:
                observer.update(self, *args)
            except Exception, msg:
                sys.stderr.write("Subject.notify() exception in update() for %r:\n" % observer)
                traceback.print_exc()

class Stack:
    def __init__(self):
        self.stack = []

    def push(self, obj):
        self.stack.append(obj)

    def pop(self):
        if len(self.stack) == 0:
            raise "Error", "stack is empty"
        obj = self.stack[-1]
        del self.stack[-1]
        return obj

    def top(self):
        if len(self.stack) == 0:
            raise "Error", "stack is empty"
        obj = self.stack[-1]
        return obj

    def is_empty(self):
        if len(self.stack) == 0:
            return 1
        return 0

    def num_elements(self):
        return len(self.stack)

